// Created by carolsail

import { ENUM_AUDIO_CLIP, ENUM_GAME_MODE, ENUM_UI_TYPE } from "../Enum";
import { StaticInstance } from './../StaticInstance';
import AudioManager from "../manager/AudioManager";
import BaseLayer from "./Baselayer";
import SdkManager from "../manager/SdkManager";
import ToastManager from "../manager/ToastManager";
import PoolManager from "../manager/PoolManager";
import UIScrollControl from "../plugins/UIScrollControl";
import DataManager from "../manager/DataManager";
import ResourceManager from "../manager/ResourceManager";
import { wxAvatar } from "../Utils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class OverLayer extends BaseLayer {

    nodePanel: cc.Node = null
    btnRestart: cc.Node = null
    btnRestartOn: cc.Node = null
    btnRestartOff: cc.Node = null
    btnShare: cc.Node = null
    btnClose: cc.Node = null
    scrollNode: cc.Node = null
    scrollItem: cc.Node = null

    isRestartTouch: boolean = false

    onLoad() {
        this.nodePanel = cc.find('style/panel', this.node)
        this.btnRestart = cc.find('buttons/btn_restart', this.nodePanel)
        this.btnRestartOn = this.btnRestart.getChildByName('on')
        this.btnRestartOff = this.btnRestart.getChildByName('off')
        this.btnShare = cc.find('buttons/btn_share', this.nodePanel)
        this.btnClose = cc.find('btn_close', this.nodePanel)
        this.btnRestartOn.on('click', this.onRestartClick, this)
        this.btnShare.on('click', this.onShareClick, this)
        this.btnClose.on('click', this.onCloseClick, this)
        this.scrollNode = cc.find('scroll', this.nodePanel)
        this.scrollItem = PoolManager.instance.getNode('OverItem')
        // DataManager.instance.wsClient.listenMsg('GameRefresh', ({ type, content }) => {
        //     if (type == 'msg_game_restart') {
        //         this.onGameRestartSync(content)
        //     } else if (type == 'msg_game_disconnect') {
        //         this.onGameDisconnectSync(content)
        //     }
        // })
    }

    onDestroy() {
        this.btnRestartOn.off('click', this.onRestartClick, this)
        this.btnShare.off('click', this.onShareClick, this)
        this.btnClose.off('click', this.onCloseClick, this)
        // DataManager.instance.wsClient.unlistenMsgAll('GameRefresh')
    }

    onEnable() {
        this.zoomIn(this.nodePanel)
        this.btnRestartOn.active = true
        this.btnRestartOff.active = false
        this.rendor()
    }

    onDisable() { }

    rendor() {
        let players = null
        if (DataManager.instance.room) players = DataManager.instance.room.players
        // 优先抵达数，然后击杀数
        let data = []
        DataManager.instance.posData.forEach((posData, i) => {
            let ep = 0
            posData.forEach(pos => {
                if (pos == 55) ep += 1
            })
            data.push({ value: posData, endpoint: ep, kill: DataManager.instance.killData[i], isAi: DataManager.instance.isAi[i], oldIndex: i })
        })
        data.sort((a, b) => {
            if (a.endpoint != b.endpoint) return a.endpoint > b.endpoint ? -1 : 1
            else if (a.kill != b.kill) return a.kill > b.kill ? -1 : 1
        })

        if (DataManager.instance.mode == ENUM_GAME_MODE.MULTIPLE) {
            if (data[0]) {
                const winner = data[0]
                if (!winner.isAi) {
                    const playerActive = DataManager.instance.room.players.find(player => player.status == 1)
                    if (playerActive.openid == DataManager.instance.user.openid) {
                        const player = DataManager.instance.room.players[winner.oldIndex]
                        if (player) {
                            // console.log('rank set')
                            const { avatar, gender, nickname, openid } = player
                            DataManager.instance.wsClient.callApi('RankSet', { rank: { openid, nickname, avatar, gender, kill: winner.kill, win: 1 } })
                        }
                    }
                }
            }
        }
        let isScrollToTop = false
        this.scrollNode.getComponent(UIScrollControl).init(this.scrollItem, data.length, cc.size(500, 110), 0, (node: cc.Node, index: number) => {
            if (!isScrollToTop) {
                isScrollToTop = true
                this.scrollNode.getComponent(cc.ScrollView).scrollToTop()
            }
            const game = data[index]
            const rank = node.getChildByName('rank')
            const main = node.getChildByName('main')
            const avatar = node.getChildByName('avatar')
            const score = main.getChildByName('score')
            const endpoint_num = score.children[0].getChildByName('num')
            const kill_num = score.children[1].getChildByName('num')
            if (game['value'].length > 0) {
                let avatarName = '222'
                let nickname = '玩家'
                if (game['isAi']) {
                    avatarName = '111'
                    nickname = 'BOT'
                }
                avatar.getChildByName('icon').getComponent(cc.Sprite).spriteFrame = ResourceManager.instance.getSprite(avatarName)
                main.getChildByName('name').getComponent(cc.Label).string = nickname
                rank.getChildByName('label').getComponent(cc.Label).string = `${index + 1}`
                if (rank.getChildByName(`icon${index + 1}`)) rank.getChildByName(`icon${index + 1}`).active = true
                endpoint_num.getComponent(cc.Label).string = `${game['endpoint']}`
                kill_num.getComponent(cc.Label).string = `${game['kill']}`
                if (DataManager.instance.mode == ENUM_GAME_MODE.MULTIPLE) {
                    if (players) {
                        const player = players[game.oldIndex]
                        if (player) {
                            main.getChildByName('name').getComponent(cc.Label).string = player.nickname
                            if (player.avatar) {
                                wxAvatar(player.avatar).then((texture: any) => {
                                    avatar.getChildByName('icon').getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture)
                                })
                            } else {
                                avatar.getChildByName('icon').getComponent(cc.Sprite).spriteFrame = ResourceManager.instance.getSprite('222')
                            }
                        }
                    }
                }
            } else {
                avatar.getChildByName('icon').getComponent(cc.Sprite).spriteFrame = null
                main.getChildByName('name').getComponent(cc.Label).string = '--'
                rank.getChildByName('label').getComponent(cc.Label).string = '-'
                endpoint_num.getComponent(cc.Label).string = '-'
                kill_num.getComponent(cc.Label).string = '-'
            }
        }, (scroll: cc.ScrollView) => {
            scroll.scrollToTop()
        })
    }

    onRestartClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        if (DataManager.instance.mode == ENUM_GAME_MODE.SINGLE) {
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MAIN, false)
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.OVER, false)
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.READY)
        } else {
            // 联机模式再来一次
            this.isRestartTouch = true
            DataManager.instance.restartCount += 1
            const room = DataManager.instance.room
            const players = []
            room.players.forEach(player => {
                if (player.status != 2) players.push(player)
            })
            room.players = players
            if (room.players.length == 1) {
                room.status = 0
                room.players.forEach(player => player.status = 0)
            } else {
                room.status = 1
            }
            const params = {
                type: 'msg_game_restart',
                room: DataManager.instance.room,
                content: {
                    room,
                    restartCount: DataManager.instance.restartCount
                }
            }
            DataManager.instance.wsClient.callApi('GameSync', params)
        }
    }

    onShareClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        if (SdkManager.instance.getPlatform()) {
            SdkManager.instance.activeShare()
        } else {
            ToastManager.instance.show('仅支持小游戏平台', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
        }
    }

    async onCloseClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        if (DataManager.instance.mode == ENUM_GAME_MODE.MULTIPLE) {
            await DataManager.instance.wsClient.callApi('ConnectLeave', { user: DataManager.instance.user })
        }
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MAIN, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.OVER, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU)
    }

    onGameRestartSync({ room, restartCount }) {
        if (!StaticInstance.uiManager.isActive(ENUM_UI_TYPE.OVER)) return
        DataManager.instance.room = room
        DataManager.instance.restartCount = restartCount
        if (room.players.length == 1) {
            // 房间只剩下一人， 回房间
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MAIN, false)
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.OVER, false)
            StaticInstance.uiManager.toggle(ENUM_UI_TYPE.ROOM)
        } else {
            if (this.isRestartTouch) {
                this.btnRestartOff.active = true
                this.btnRestartOn.active = false
                this.isRestartTouch = false
            }
            if (restartCount >= room.players.length) {
                // 数据
                DataManager.instance.posData = [[], [], [], []]
                DataManager.instance.isAi = [true, true, true, true]
                if (DataManager.instance.isAiCover) {
                    DataManager.instance.posData = [
                        [-2, -2, -2, -2],
                        [-2, -2, -2, -2],
                        [-2, -2, -2, -2],
                        [-2, -2, -2, -2]
                    ]
                }
                DataManager.instance.room.players.forEach((_, index) => {
                    DataManager.instance.posData[index] = [-2, -2, -2, -2]
                    DataManager.instance.isAi[index] = false
                })
                // 身份
                const role = DataManager.instance.room.players.findIndex(player => player.openid == DataManager.instance.user.openid)
                DataManager.instance.role = role
                // 回合
                DataManager.instance.round = 0
                StaticInstance.uiManager.toggle(ENUM_UI_TYPE.OVER, false)
                StaticInstance.gameManager.onGameStart()
            }
        }
    }

    onGameDisconnectSync({ room }) {
        if (!StaticInstance.uiManager.isActive(ENUM_UI_TYPE.OVER)) return
        DataManager.instance.room = room
        if (room.players.length == 1 && this.btnRestartOff.active) {
            room.status = 0
            room.players.forEach(player => player.status = 0)
            const params = {
                type: 'msg_game_restart',
                room: DataManager.instance.room,
                content: {
                    room,
                    restartCount: DataManager.instance.restartCount
                }
            }
            DataManager.instance.wsClient.callApi('GameSync', params)
        } else {
            if (room.players.length == DataManager.instance.restartCount) {
                room.status = 1
                const params = {
                    type: 'msg_game_restart',
                    room: DataManager.instance.room,
                    content: {
                        room,
                        restartCount: DataManager.instance.restartCount
                    }
                }
                DataManager.instance.wsClient.callApi('GameSync', params)
            }
        }
    }
}
